package cn.jjxx.modules.te.controller;

import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.annotations.TableName;

import org.framework.superutil.thirdparty.excel.ExcelDataFormatter;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import cn.jjxx.modules.common.bean.UploadExcel;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.utils.UserUtils;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.modules.te.entity.TeMainMaterial;
import cn.jjxx.modules.te.entity.TeMaterialComparison;
import cn.jjxx.modules.te.service.ITeMaterialComparisonService;
import cn.jjxx.modules.map.service.ICommonMapService;
/**   
 * @Title: 材料对比
 * @Description: 材料对比
 * @author TianShixi
 * @date 2022-01-12 13:59:21
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/te/tematerialcomparison")
@RequiresPathPermission("te:tematerialcomparison")
public class TeMaterialComparisonController extends BaseBeanController<TeMaterialComparison> {

    @Autowired
    protected ITeMaterialComparisonService teMaterialComparisonService;
    @Autowired
    protected ICommonMapService commonMapService;

	/**
	 * @Description: 根据获取材料对比的实体数据 .<br>
	 * @param id 主键Id.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    public TeMaterialComparison get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return teMaterialComparisonService.selectById(id);
        } else {
            return newModel();
        }
    }

	/**
	 * @Description: 跳转至材料对比的列表界面 .<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

	/**
	 * @Description: 材料对比的列表界面获取列表结果 .<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<TeMaterialComparison> entityWrapper = new EntityWrapper<TeMaterialComparison>(entityClass);
        entityWrapper.orderBy("sort");
        propertyPreFilterable.addQueryProperty("id");
        String size = request.getParameter("page.size");
        if(StringUtils.isEmpty(size)) {
            List<TeMaterialComparison> list = teMaterialComparisonService.selectList(entityWrapper);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("results", list);
            map.put("page", 1);
            map.put("rows", list.size());
            map.put("total", list.size());
            map.put("totalPages", 1);
            String content = JSON.toJSONString(map);
	        StringUtils.printJson(response, content);
        }else {
            // 预处理
            QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
            SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
            PageJson<TeMaterialComparison> pagejson = new PageJson<TeMaterialComparison>(teMaterialComparisonService.list(queryable,entityWrapper));
            String content = JSON.toJSONString(pagejson, filter);
            StringUtils.printJson(response, content);
        }
    }

	/**
	 * @Description: 跳转至材料对比的添加界面 .<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        return display("edit");
    }
    
	/**
	 * @Description: 新增材料对比的数据 .<br>
	 * @param teMaterialComparison 材料对比实体类.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") TeMaterialComparison teMaterialComparison, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(teMaterialComparison, request, response, result);
    }
	/**
	 * @Description: 跳转至材料对比的更新界面 .<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        TeMaterialComparison teMaterialComparison = get(id);
        model.addAttribute("data", teMaterialComparison);
        return display("edit");
    }

	/**
	 * @Description: 修改材料对比的数据 .<br>
	 * @param teMaterialComparison 材料对比实体类.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") TeMaterialComparison teMaterialComparison, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(teMaterialComparison, request, response, result);
    }
	/**
	 * @Description: 执行保存材料对比的数据操作 .<br>
	 * @param teMaterialComparison 材料对比实体类.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(TeMaterialComparison teMaterialComparison, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(teMaterialComparison, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(teMaterialComparison.getId())) {
                teMaterialComparisonService.insert(teMaterialComparison);
            } else {
                teMaterialComparisonService.insertOrUpdate(teMaterialComparison);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

	/**
	 * @Description: 单条删除材料对比 .<br>
	 * @param id 单据Id.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        TableName table = TeMaterialComparison.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
        	List<String> ids = Arrays.asList(id.split(","));
        	//得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, ids);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("删除失败,"+quoteMsg);
				return ajaxJson;
			}
            teMaterialComparisonService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 执行保存材料对比的数据操作 .<br>
	 * @param ids 单据Id集合.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("批量删除成功");
        TableName table = TeMaterialComparison.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            //得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, idList);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("批量删除失败,"+quoteMsg);
				return ajaxJson;
			}
            teMaterialComparisonService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("批量删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 跳转至材料对比的查看界面 .<br>
	 * @param ids 单据Id.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        TeMaterialComparison teMaterialComparison = get(id);
        model.addAttribute("data", teMaterialComparison);
        return display("edit");
    }

	/**
	 * @Description: 验证材料对比功能数据的唯一性 .<br>
	 * @param duplicateValid 校验实体类.<br>
	 * @author TianShixi .<br>
	 * @date 2022-01-12 13:59:21.<br>
	 */
    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<TeMaterialComparison> entityWrapper = new EntityWrapper<TeMaterialComparison>(entityClass);
            valid = teMaterialComparisonService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }
    
    
    
    
    
    
    
    
    
    /**
     * @Description: 得到可以被审核的单据 .<br>
     * @param bills 单据Id集合.<br>
     * @param status 可操作状态.<br>
     * @author TianShixi .<br>
     * @date 2022-01-12 13:59:21 .<br>
     */
    private List<String> getAllowOptBills(List<String> bills,String status){
    	EntityWrapper<TeMaterialComparison> wrapper = new EntityWrapper<TeMaterialComparison>();
    	wrapper.in("id", bills);
    	wrapper.eq("status", status);
    	List<TeMaterialComparison> list = teMaterialComparisonService.selectList(wrapper);
    	bills = new ArrayList<String>();
    	for(TeMaterialComparison bean:list){
    		bills.add(bean.getId());
    	}
    	return bills;
    }
    
    /**
     * @Description: 设置批量更新参数 .<br>
     * @param bills 可以操作的Id集合.<br>
     * @param newStatus 被修改的状态设置值.<br>
     * @author TianShixi .<br>
     * @date 2022-01-12 13:59:21 .<br>
     */
    private List<TeMaterialComparison> setBacthUpdate(List<String> bills,String newStatus){
    	List<TeMaterialComparison> list = new ArrayList<TeMaterialComparison>();
    	User user = UserUtils.getUser();
    	if(bills.size()>0){
    		list = teMaterialComparisonService.selectBatchIds(bills);
        	for(TeMaterialComparison bean:list){
        		if(newStatus.equals(String.valueOf(BillConfig.SAVE))||
        				newStatus.equals(String.valueOf(BillConfig.SUBMIT))){
        		}
        	}
    	}
    	return list;
    }
}
